package com.gsafety.wellsfort.controller.organization;

import com.alibaba.fastjson.JSONObject;
import com.gsafety.wellsfort.annotation.CheckToken;
import com.gsafety.wellsfort.common.constant.IConstant;
import com.gsafety.wellsfort.common.enums.*;
import com.gsafety.wellsfort.common.util.ApiResponse;
import com.gsafety.wellsfort.common.util.JwtUtil;
import com.gsafety.wellsfort.common.util.ResultCode;
import com.gsafety.wellsfort.config.CacheManager;
import com.gsafety.wellsfort.dao.organization.StudentLoginRelDAO;
import com.gsafety.wellsfort.domain.model.organization.Student;
import com.gsafety.wellsfort.domain.model.organization.StudentLoginRel;
import com.gsafety.wellsfort.domain.model.organization.WxCustomer;
import com.gsafety.wellsfort.domain.model.security.UserLogin;
import com.gsafety.wellsfort.domain.vo.WeChatLoginVO;
import com.gsafety.wellsfort.service.organization.IStudentService;
import com.gsafety.wellsfort.service.organization.IWeChatService;
import com.gsafety.wellsfort.service.security.IUserLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@Api(description = "微信登录,用户绑定接口")
@RestController
@Slf4j
@RequestMapping("/api/customer")
public class WeChatController {

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private IWeChatService weChatService;

    @Autowired
    private IUserLoginService userLoginService;

    @Autowired
    private IStudentService studentService;

    @Autowired
    private StudentLoginRelDAO studentLoginRelDAO;

    @ApiOperation(value = "QQ微信登录接口")
    @CheckToken(value = false)
    @PostMapping("/weChatLogin")
    public ApiResponse weChatLogin(@RequestBody WeChatLoginVO weChatLoginVO) {
        JSONObject result = new JSONObject();
        //判断微信用户是否第一次登录,第一次登录需要绑定账号
        WxCustomer wxCustomer = weChatService.getByOpenId(weChatLoginVO.getOpenId());
        if (wxCustomer == null) {
            int insert = weChatService.add(weChatLoginVO);
            if (insert > 0) {
                result.put("hasBindPhone", false);
                return ApiResponse.success(result);
            }
        } else {
            if (wxCustomer.getLoginId() == null) {
                result.put("hasBindPhone", false);
            } else {
                //不为空，判断是否绑定学生了
                UserLogin userLogin = userLoginService.getUserLoginById(wxCustomer.getLoginId());
                String token = JwtUtil.createJWT(8 * 60 * 60 * 1000, userLogin);
                //token ip添加进入缓存
                cacheManager.setHashKey(RedisPrefixEnum.ACCOUNT_TOKEN_UNIQUE.getPrefix(), userLogin.getAccount(), token);
                Student student = studentService.getByLoginId(userLogin.getId());
                result.put(IConstant.TOKEN, token);
                result.put("hasBindPhone", true);
                if (student == null) {
                    result.put("hasBindStudent", false);
                } else {
                    result.put("hasBindStudent", true);
                }
                return ApiResponse.success(result);
            }
            return ApiResponse.success(result);
        }
        return ApiResponse.error();
    }


    @ApiOperation(value = "QQ微信绑定登录账号")
    @CheckToken(value = false)
    @PostMapping("/weChatBind")
    public ApiResponse weChatBind(@RequestBody WeChatLoginVO weChatLoginVO) {
        //判断微信用户是否第一次登录,第一次登录需要绑定账号
        JSONObject result = new JSONObject();
        if (!"1".equals(weChatLoginVO.getExt1()) && !"0".equals(weChatLoginVO.getExt1())) {
            return ApiResponse.error(ResultCode.INVALID_PARAM);
        }
        WxCustomer wxCustomer = weChatService.getByOpenId(weChatLoginVO.getOpenId());
        if (wxCustomer == null) {
            return ApiResponse.error(ResultCode.REQUEST_PARAMETER_IS_NOT_LEGAL);
        }
        if (wxCustomer.getLoginId() != null) {
            return ApiResponse.error(ResultCode.ACCOUNT_HAS_BIND_WX);
        }
        UserLogin userLogin = userLoginService.getUserLoginByAccount(weChatLoginVO.getPhone());
        if (userLogin == null) {
            //微信绑定手机号,若手机号不存在,在数据库中登录表中插入相应记录
            //免注册登录,直接注册登录(密码设置为空,只能免注册登录，不允许账号密码登录)
            UserLogin userLoginDO = UserLogin.builder().account(weChatLoginVO.getPhone()).password(null).
                    originalPassword(null).type(UserTypeEnum.APP.getCode().byteValue()).status(StatusEnum.ENABLE.getValue().byteValue()).
                    creator(IConstant.SYSTEM_OPERATOR).operator(IConstant.SYSTEM_OPERATOR).created(new Date()).modified(new Date()).build();
            userLoginService.add(userLoginDO);
            userLogin = userLoginDO;
        }
        List<WxCustomer> list = weChatService.selectByLoginId(userLogin.getId());
        if (list != null && list.size() > 0) {
            for (WxCustomer customer : list) {
                if (customer != null && StringUtils.isNotEmpty(customer.getExt1()) && customer.getExt1().equals(weChatLoginVO.getExt1())) {
                    //输入手机号号码已经绑定qq、微信,则替换原来数据
                    weChatService.delete(customer.getId());
                }
            }
        }
        WxCustomer newWxCustomer = new WxCustomer();
        newWxCustomer.setId(wxCustomer.getId());
        newWxCustomer.setLoginId(userLogin.getId());
        newWxCustomer.setModified(new Date());
        int update = weChatService.update(newWxCustomer);
        if (update > 0) {
            String token = JwtUtil.createJWT(8 * 60 * 60 * 1000, userLogin);
            //token ip添加进入缓存
            cacheManager.setHashKey(RedisPrefixEnum.ACCOUNT_TOKEN_UNIQUE.getPrefix(), userLogin.getAccount(), token);
            ///判断是否绑定学生了
            Student student = studentService.getByLoginId(userLogin.getId());
            if (student == null) {
                //游客模式,添加虚拟学生
                Student stu = studentService.getAllByLoginId(userLogin.getId());
                if (stu == null) {
                    //游客模式,添加虚拟学生
                    Student studentDo = new Student();
                    studentDo.setSchoolId(SchoolEnum.FICTITIOUS_SCHOOL.value);
                    studentDo.setClassId(ClassEnum.FICTITIOUS_CLASS.value);
                    studentDo.setName(userLogin.getAccount());
                    studentDo.setCreator("system");
                    studentDo.setOperator("system");
                    studentDo.setParentPhone(userLogin.getAccount());
                    studentDo.setParentName(userLogin.getAccount());
                    //虚拟学生标识
                    studentDo.setExt1("0");
                    studentService.addStudent(studentDo);
                    StudentLoginRel studentLoginRel = new StudentLoginRel();
                    studentLoginRel.setLoginId(userLogin.getId());
                    studentLoginRel.setStudentId(studentDo.getId());
                    studentLoginRel.setCreated(new Date());
                    studentLoginRel.setModified(new Date());
                    studentLoginRelDAO.insertSelective(studentLoginRel);
                    result.put("hasBindStudent", false);
                }
            } else {
                result.put("hasBindStudent", true);
            }
            result.put(IConstant.TOKEN, token);
            return ApiResponse.success(result);
        }
        return ApiResponse.error();
    }
}
